from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from meiduo_project import settings


def generate_verify_token(user_id):
    """
    对user_id加密 返回
    :param user_id: 当前登录用户id
    :return: token
    """
    serializer = Serializer(settings.SECRET_KEY, 3600 * 24 * 2)
    data = {'user_id': user_id}
    # serializer.dumps(数据),返回bytes类型
    token = serializer.dumps(data).decode()

    return token


def check_verify_token(token):
    """
    对token解密  返回user_id
    :param token
    :return: user_id
    """
    serializer = Serializer(settings.SECRET_KEY, 3600 * 24 * 2)

    # serializer.dumps(数据),返回bytes类型
    try:
        user_id_dict = serializer.loads(token)
        user_id = user_id_dict.get("user_id")
        return user_id
    except:
        print("签名过期")
        return None


if __name__ == '__main__':
    token = generate_verify_token(123)
    print(token)
    userid = check_verify_token(token)
    print(userid)
